package controllers

import dao._
import implicits.Implicits._
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import java.nio.file.Files
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 11/5/2020
 */
class TreeController @Inject()(cc: ControllerComponents)(
  implicit val prokaryoteDao: ProkaryoteDao,
  implicit val bioSampleDao: BioSampleDao,
  implicit val assemblyDao: AssemblyDao,
) extends AbstractController(cc) {

  def toIndex = Action { implicit request =>
    Ok(views.html.tree.index())
  }

  def getNwk = Action { implicit request =>
    val file = new File(Tool.phyDir, "tree.nwk")
    val str = file.str.trim
    Ok(Json.obj("str" -> str))
  }

  def downloadTree = Action { implicit request =>
    val data = FormTool.svgForm.bindFromRequest().get
    val dataFile = Files.createTempFile("tmp", ".svg").toFile
    val str = data.svgHtml.replaceAll("</svg>", "\n" + Utils.phylotreeCss + "</svg>")
    str.toFile(dataFile)
    Ok.sendFile(dataFile, onClose = () => {
      Files.deleteIfExists(dataFile.toPath)
    }).withHeaders(
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> "attachment; filename=tree.svg",
      CONTENT_TYPE -> "application/x-download"
    )
  }


}
